<?php
/*
 * @Author: zhx zhx.0830@qq.com
 * @Date: 2023-09-07 14:31:18
 * @LastEditors: zhx zhx.0830@qq.com
 * @LastEditTime: 2023-09-08 14:21:28
 * @FilePath: \new-version-saas\app\Http\Middleware\LogOperation.php
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */

namespace App\Http\Middleware;

use App\Models\admin\OperationLogs;
use Closure;
use Illuminate\Support\Facades\Log;

/**
 * 操作日志中间件
 */
class LogOperation
{
    protected $secretFields = [
        'password',
        'password_confirmation',
    ];

    //protected $defaultAllowedMethods = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'];
    /**
     * 操作类型
     *
     * @PATCH ajax获取列表
     *
     * @POST 添加
     *
     * @PUT 编辑
     *
     * @DELETE 删除
     */
    protected $defaultAllowedMethods = ['POST', 'PUT', 'DELETE'];

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        if (in_array($request->method(), $this->defaultAllowedMethods)) {
            $log = [
                'user_id' => $request->user['id'] ? $request->user['id'] : 0,
                'platform' => isset($request->user['platform']['id']) ? $request->user['platform']['id'] : 0,
                'username' => $request->user['name'] ? $request->user['name'] : '',
                'path' => substr($request->path(), 0, 255),
                'method' => $request->method(),
                'ip' => $request->getClientIp(),
                'input' => $this->formatInput($request->input()),
            ];

            $result = OperationLogs::create($log);
            if (! $result) {
                Log::info('日期：'.date('Y-m-dH:i:s').' ,log : '.var_export($log));
            }
        }

        return $response;
    }

    /**
     * @return string
     */
    protected function formatInput(array $input)
    {
        foreach ($this->secretFields as $field) {
            if (isset($input[$field])) {
                $input[$field] = \Illuminate\Support\Str::limit($input[$field], 3, '******');
            }
        }

        unset($input['user']);
        unset($input['menu']);
        unset($input['setting']);

        return json_encode($input, JSON_UNESCAPED_UNICODE);
    }
}
